<template>
  <div class="reservation-management-container">
    <el-card class="page-header-card">
      <div class="page-header">
        <div class="page-title">
          <h2>预约管理</h2>
          <p>管理用户车位预约申请，审核预约请求</p>
        </div>
      </div>
    </el-card>
    
    <!-- 搜索和过滤 -->
    <el-card class="filter-card">
      <div class="filter-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="车牌号码">
            <el-input v-model="searchForm.plateNumber" placeholder="请输入车牌号码" clearable />
          </el-form-item>
          <el-form-item label="预约状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px;">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="预约时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="width: 260px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><RefreshRight /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <!-- 预约列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>预约列表</span>
          <div class="header-actions">
            <el-button type="success" plain @click="handleBatchApprove" :disabled="selectedReservations.length === 0">
              <el-icon><Check /></el-icon>批量审核通过
            </el-button>
            <el-button type="danger" plain @click="handleBatchReject" :disabled="selectedReservations.length === 0">
              <el-icon><Close /></el-icon>批量拒绝
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="reservationList"
        style="width: 100%"
        border
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" min-width="100" />
        <el-table-column prop="plateNumber" label="车牌号码" min-width="110" />
        <el-table-column prop="spaceNumber" label="车位号" min-width="100" />
        <el-table-column label="预约时间" min-width="200">
          <template #default="scope">
            {{ formatDateTime(scope.row.startTime) }} 至 {{ formatDateTime(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="预约状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.statusDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="提交时间" min-width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 0"
              type="success"
              size="small"
              @click="handleApprove(scope.row)"
            >
              审核通过
            </el-button>
            <el-button
              v-if="scope.row.status === 0"
              type="danger"
              size="small"
              @click="handleReject(scope.row)"
            >
              拒绝
            </el-button>
            <el-button type="primary" size="small" @click="handleViewDetail(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 预约详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="预约详情"
      width="600px"
    >
      <el-descriptions bordered :column="1" border size="large">
        <el-descriptions-item label="预约ID">{{ currentReservation.id }}</el-descriptions-item>
        <el-descriptions-item label="用户信息">
          {{ currentReservation.username }} ({{ currentReservation.realName }})
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentReservation.phone }}</el-descriptions-item>
        <el-descriptions-item label="车牌号码">{{ currentReservation.plateNumber }}</el-descriptions-item>
        <el-descriptions-item label="车位信息">
          {{ currentReservation.spaceNumber }}
        </el-descriptions-item>
        <el-descriptions-item label="预约时间">
          {{ formatDateTime(currentReservation.startTime) }} 至 {{ formatDateTime(currentReservation.endTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="预约费用">
          <span class="fee-text">¥{{ currentReservation.fee.toFixed(2) }}</span>
          <el-tag v-if="currentReservation.isPaid === 1" type="success" size="small">已支付</el-tag>
          <el-tag v-else type="danger" size="small">未支付</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="预约状态">
          <el-tag :type="getStatusType(currentReservation.status)">
            {{ currentReservation.statusDesc }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注信息">
          {{ currentReservation.remark || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="提交时间">
          {{ formatDateTime(currentReservation.createdAt) }}
        </el-descriptions-item>
      </el-descriptions>
      
      <div class="dialog-footer" v-if="currentReservation.status === 0">
        <el-button type="success" @click="handleApprove(currentReservation)">审核通过</el-button>
        <el-button type="danger" @click="handleReject(currentReservation)">拒绝</el-button>
      </div>
    </el-dialog>
    
    <!-- 审核确认对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      :title="reviewType === 'approve' ? '审核通过' : '拒绝预约'"
      width="500px"
    >
      <div class="review-content">
        <p>{{ reviewType === 'approve' ? '确定通过以下预约申请？' : '确定拒绝以下预约申请？' }}</p>
        <div v-if="selectedReservations.length > 0" class="selected-list">
          <div v-for="(item, index) in selectedReservations" :key="index" class="selected-item">
            <span>{{ item.plateNumber }}</span>
            <span>{{ item.spaceNumber }}</span>
            <span>{{ formatDateShort(item.startTime) }}</span>
          </div>
        </div>
        <div v-else>
          <p>
            <strong>车牌号码：</strong>{{ currentReservation.plateNumber }}<br>
            <strong>车位号：</strong>{{ currentReservation.spaceNumber }}<br>
            <strong>预约时间：</strong>{{ formatDateTime(currentReservation.startTime) }} 至 {{ formatDateTime(currentReservation.endTime) }}
          </p>
        </div>
        
        <el-form :model="reviewForm" label-width="80px" style="margin-top: 20px;">
          <el-form-item label="备注">
            <el-input
              v-model="reviewForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入审核备注（可选）"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button :type="reviewType === 'approve' ? 'success' : 'danger'" @click="submitReview">
            确定{{ reviewType === 'approve' ? '通过' : '拒绝' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, RefreshRight, Check, Close, View } from '@element-plus/icons-vue'
import { getReservationList, reviewReservation, batchReviewReservations } from '@/api/reservation'

// 状态选项
const statusOptions = [
  { value: 0, label: '待审核' },
  { value: 1, label: '已确认' },
  { value: 2, label: '已使用' },
  { value: 3, label: '已取消' },
  { value: 4, label: '已拒绝' }
]

// 加载状态
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  plateNumber: '',
  status: '',
  dateRange: []
})

// 预约列表数据
const reservationList = ref([])

// 已选择的预约
const selectedReservations = ref([])

// 当前查看的预约详情
const currentReservation = reactive({
  id: '',
  username: '',
  realName: '',
  phone: '',
  plateNumber: '',
  spaceNumber: '',
  startTime: '',
  endTime: '',
  status: 0,
  fee: 0,
  isPaid: 0,
  remark: '',
  createdAt: ''
})

// 对话框控制
const detailDialogVisible = ref(false)
const reviewDialogVisible = ref(false)
const reviewType = ref('approve') // 'approve' 或 'reject'

// 审核表单
const reviewForm = reactive({
  remark: ''
})

// 生命周期钩子
onMounted(() => {
  fetchReservations()
})

// 获取预约列表
const fetchReservations = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      plateNumber: searchForm.plateNumber || undefined,
      status: searchForm.status || undefined,
      startTimeBegin: searchForm.dateRange?.[0] || undefined,
      startTimeEnd: searchForm.dateRange?.[1] || undefined,
      isAdmin: true // 添加管理员标识
    }
    
    const response = await getReservationList(params)
    if (response.code === 200) {
      reservationList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取预约列表失败')
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',  // 待审核
    1: 'success',  // 已确认
    2: 'info',     // 已使用
    3: 'info',     // 已取消
    4: 'danger'    // 已拒绝
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已确认',
    2: '已使用',
    3: '已取消',
    4: '已拒绝'
  }
  return texts[status] || '未知状态'
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  const date = new Date(dateTimeStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 格式化短日期（仅显示日期）
const formatDateShort = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  const date = new Date(dateTimeStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchReservations()
}

// 重置搜索
const resetSearch = () => {
  searchForm.plateNumber = ''
  searchForm.status = ''
  searchForm.dateRange = []
  handleSearch()
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedReservations.value = selection
}

// 处理查看详情
const handleViewDetail = (row) => {
  Object.assign(currentReservation, row)
  detailDialogVisible.value = true
}

// 处理审核通过单条记录
const handleApprove = (row) => {
  if (row.status !== 0) {
    ElMessage.warning('只能审核待审核状态的预约')
    return
  }
  Object.assign(currentReservation, row)
  selectedReservations.value = []
  reviewType.value = 'approve'
  reviewForm.remark = ''
  reviewDialogVisible.value = true
}

// 处理拒绝单条记录
const handleReject = (row) => {
  if (row.status !== 0) {
    ElMessage.warning('只能审核待审核状态的预约')
    return
  }
  Object.assign(currentReservation, row)
  selectedReservations.value = []
  reviewType.value = 'reject'
  reviewForm.remark = ''
  reviewDialogVisible.value = true
}

// 处理批量审核通过
const handleBatchApprove = () => {
  // 过滤出待审核的预约
  const pendingReservations = selectedReservations.value.filter(item => item.status === 0)
  
  if (pendingReservations.length === 0) {
    ElMessage.warning('已选记录中没有待审核的预约')
    return
  }
  
  selectedReservations.value = pendingReservations
  reviewType.value = 'approve'
  reviewForm.remark = ''
  reviewDialogVisible.value = true
}

// 处理批量拒绝
const handleBatchReject = () => {
  // 过滤出待审核的预约
  const pendingReservations = selectedReservations.value.filter(item => item.status === 0)
  
  if (pendingReservations.length === 0) {
    ElMessage.warning('已选记录中没有待审核的预约')
    return
  }
  
  selectedReservations.value = pendingReservations
  reviewType.value = 'reject'
  reviewForm.remark = ''
  reviewDialogVisible.value = true
}

// 提交审核结果
const submitReview = async () => {
  const newStatus = reviewType.value === 'approve' ? 1 : 4
  const actionText = reviewType.value === 'approve' ? '审核通过' : '拒绝'
  
  try {
    // 处理批量审核
    if (selectedReservations.value.length > 0) {
      const res = await batchReviewReservations({
        ids: selectedReservations.value.map(item => item.id),
        status: newStatus,
        remark: reviewForm.remark
      })
      
      if (res.code === 200) {
        ElMessage.success(`已${actionText} ${selectedReservations.value.length} 条预约记录`)
        fetchReservations() // 刷新列表
      } else {
        ElMessage.error(res.message || `批量${actionText}失败`)
      }
    } 
    // 处理单条审核
    else {
      const res = await reviewReservation(currentReservation.id, {
        status: newStatus,
        remark: reviewForm.remark
      })
      
      if (res.code === 200) {
        ElMessage.success(`已${actionText}预约：${currentReservation.plateNumber}`)
        fetchReservations() // 刷新列表
      } else {
        ElMessage.error(res.message || `${actionText}失败`)
      }
    }
    
    // 关闭对话框
    reviewDialogVisible.value = false
    
    // 如果是从详情对话框打开的，也关闭
    if (selectedReservations.value.length === 0) {
      detailDialogVisible.value = false
    }
    
    // 清空选择
    selectedReservations.value = []
  } catch (error) {
    console.error(`${actionText}失败:`, error)
    ElMessage.error(`${actionText}失败，请重试`)
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchReservations()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchReservations()
}
</script>

<style scoped>
.reservation-management-container {
  padding: 20px;
  min-height: calc(100vh - 180px);
}

.page-header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0 0 5px 0;
  font-size: 22px;
}

.page-title p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.fee-text {
  font-weight: bold;
  color: #f56c6c;
  margin-right: 10px;
}

.selected-list {
  max-height: 150px;
  overflow-y: auto;
  margin: 10px 0;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 5px;
}

.selected-item {
  display: flex;
  justify-content: space-between;
  padding: 5px;
  border-bottom: 1px solid #ebeef5;
}

.selected-item:last-child {
  border-bottom: none;
}

@media screen and (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .page-actions {
    margin-top: 15px;
    width: 100%;
  }
  
  .filter-section .search-form {
    display: flex;
    flex-direction: column;
  }
  
  .filter-section .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 10px;
    display: flex;
    width: 100%;
  }
  
  .header-actions .el-button {
    flex: 1;
  }
  
  .pagination-container {
    justify-content: center;
  }
  
  .dialog-footer {
    flex-direction: column;
    gap: 10px;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

@media screen and (max-width: 576px) {
  .reservation-management-container {
    padding: 10px;
  }
  
  .filter-card, .table-card {
    margin-bottom: 10px;
  }
  
  .el-date-picker {
    width: 100% !important;
  }
  
  .el-descriptions__label {
    width: 100px;
  }
}
</style> 